import axios from 'axios';
import { getToken } from './auth';
import { Message, Loading } from 'element-ui';
import router from '@/router';
import store from '@/store';

/**
 * 创建axios实例
 */
const service = axios.create({
  baseURL: '/api',
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

let loadingInstance = null;
let loadingCount = 0;

/**
 * 显示加载动画
 */
function showLoading(text = '加载中...') {
  if (loadingCount === 0) {
    loadingInstance = Loading.service({
      lock: true,
      text: text,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    store.dispatch('app/showLoading');
  }
  loadingCount++;
}

/**
 * 隐藏加载动画
 */
function hideLoading() {
  loadingCount--;
  if (loadingCount <= 0) {
    loadingCount = 0;
    if (loadingInstance) {
      loadingInstance.close();
      loadingInstance = null;
    }
    
    store.dispatch('app/hideLoading');
  }
}

/**
 * 配置请求拦截器
 */
service.interceptors.request.use(config => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  
  if (config.showLoading !== false) {
    showLoading(config.loadingText || '加载中...');
  }
  
  return config;
}, error => {
  hideLoading();
  console.log(error);
  return Promise.reject(error);
});

/**
 * 配置响应拦截器
 */
service.interceptors.response.use(res => {
  if (res.config.showLoading !== false) {
    hideLoading();
  }
  
  const data = res.data;
  
  if (data.code !== 200 && data.code !== 0) {
    Message({
      message: data.message || '请求出错',
      type: 'error',
      duration: 5 * 1000
    });
    
    if (data.code === 401) {
      store.dispatch('logout').then(() => {
        router.push('/login');
      });
    }
    
    return Promise.reject(new Error(data.message || '请求出错'));
  } else {
    return data;
  }
}, error => {
  hideLoading();
  
  console.log('响应错误:', error);

  let message = '网络错误';
  if (error.response) {
    switch (error.response.status) {
      case 400:
        message = '请求错误';
        break;
      case 401:
        message = '未授权，请重新登录';
        store.dispatch('logout').then(() => {
          router.push('/login');
        });
        break;
      case 403:
        message = '拒绝访问';
        break;
      case 404:
        message = '请求地址不存在';
        break;
      case 500:
        message = '服务器内部错误';
        break;
      default:
        message = `连接错误 ${error.response.status}`;
    }
  } else if (error.request) {
    message = '服务器无响应';
  } else {
    message = error.message;
  }
  
  Message({
    message: message,
    type: 'error',
    duration: 5 * 1000
  });
  
  return Promise.reject(error);
});

/**
 * 封装GET请求
 */
export function get (url, params, config = {}) {
  return service.get(url, { params, ...config });
}

/**
 * 封装POST请求
 */
export function post(url, data, config = {}) {
  return service.post(url, data, config);
}

/**
 * 封装PUT请求
 */
export function put(url, data, config = {}) {
  return service.put(url, data, config);
}

/**
 * 封装DELETE请求
 */
export function del(url, params, config = {}) {
  return service.delete(url, { params, ...config });
}

/**
 * 封装文件上传请求
 */
export function upload(url, file, config = {}) {
  const formData = new FormData();
  formData.append('file', file);
  
  return service.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    ...config
  });
}

/**
 * 导出axios实例和请求方法
 */
export default {
  service,
  get,
  post,
  put,
  delete: del,
  upload
};